package siwi.map.android;

import java.util.ArrayList;
import java.util.Random;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.MenuItem;
import com.wmw.DataPool.OrdersForm;
import com.wmw.DataPool.OrdersFormItem;
import com.wmw.Utility.Common;
import com.wmw.Utility.DBConstant;
import com.wmw.Utility.DBConstant.DatabaseHelper;
import com.wmw.Utility.MSG;
import com.wmw.Utility.RegularExpression;

public class MyHome extends SherlockFragment {
	// 1. 若返回之前list,重新刷新了,之前记忆的position是不是就变了.
	private static Activity _Activity = null;
	private static final int _ReceiveOerdersForm = 1;
	int mNum;
	private ArrayList<OrdersForm> _list = new ArrayList<OrdersForm>();
	private ExAdapter adapter;

	private PullDownView pullListView;
	private ProgressBar moreProgressBar;
	private ScrollOverListView listView;

	private long _refreshDBNumOneTime = 3;
	private long _curfreshDBIdx = 0;
	private long _totalDBOrdersFormNum = 0;

	private View _noMsgLayout;

	private DatabaseHelper _openDBHelper;

	private int _curSelected;

	View _sureToFeedback;
	EditText _etFeedback;

	/**
	 * When creating, retrieve this instance's number from its arguments.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		_Activity = getActivity();

		Bundle bundle = getArguments();
		_openDBHelper = bundle != null ? (DatabaseHelper) bundle
				.getSerializable(MSG.DataBase) : null;

		createMyHomeTables(_openDBHelper.getWritableDatabase());
		setHasOptionsMenu(true);
	}

	/**
	 * The Fragment's UI is just a simple text view showing its instance number.
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.d(Common.GetLineInfo(), "current number -" + mNum);
		View v = inflater.inflate(R.layout.my_home, container, false);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initViews();
		initData();
	}

	/**
	 * This method is called when the sending activity has finished, with the
	 * result it supplied.
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// You can use the requestCode to select between multiple child
		// activities you may have started. Here there is only one thing
		// we launch.
		if (requestCode == _ReceiveOerdersForm) {
			if (resultCode != Activity.RESULT_CANCELED) {
				Common.toastInfo(getActivity(), "通知接收此订单");
				removeOrderFormFromDB(_list.get(_curSelected).get_id());
				desDBIdx();

				// Add to history.
				OrdersForm of = _list.get(_curSelected);
				DBConstant.insertOneOrderFormToHistoryDB(
						_openDBHelper.getWritableDatabase(), of);
				int num = of.get_items().length;
				for (int i = 0; i < num; ++i)
					DBConstant.insertOneOrderFormItemToHistoryDB(
							_openDBHelper.getWritableDatabase(),
							of.get_items()[i], of.get_id());

				_list.remove(_curSelected);
				adapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	public void onStart() {
		super.onStart();

	}

	@Override
	public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu,
			com.actionbarsherlock.view.MenuInflater inflater) {
		inflater.inflate(R.menu.my_home_action_bar, menu);

		final MenuItem refresh = (MenuItem) menu.findItem(R.id.MHAB_Refresh);
		refresh.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				new Handler().postDelayed(new Runnable() {
					public void run() {
						// TODO
						Common.toastInfo(getActivity(), "通知获取订单");
						addOrdersForm(1);
						refresh.setActionView(null);

						showPartItems(_curfreshDBIdx);
						incDBIdx();
						adapter.notifyDataSetChanged();
					}
				}, 1000);

				return false;
			}
		});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		_Activity = null;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.MHAB_Refresh:
			item.setActionView(R.layout.indeterminate_progress_action);
			break;
		}
		return false;
	}

	static MyHome newInstance(DatabaseHelper dbHelper) {
		MyHome f = new MyHome();

		Bundle args = new Bundle();
		args.putSerializable(MSG.DataBase, dbHelper);
		f.setArguments(args);

		return f;
	}

	private void initViews() {
		Activity activity = getActivity();

		pullListView = (PullDownView) activity.findViewById(R.id.MH_List);
		pullListView.enableAutoFetchMore(true, 0);
		listView = pullListView.getListView();
		adapter = new ExAdapter(activity);
		listView.setAdapter(adapter);

		_noMsgLayout = activity.findViewById(R.id.MH_NoMsgLayout);

		_etFeedback = (EditText) activity.findViewById(R.id.MH_Feedback);
		ImageView ivClearFeedback = (ImageView) getActivity().findViewById(
				R.id.MH_ClearFeedback);
		final InputBox _feedback = new InputBox(activity, _etFeedback,
				ivClearFeedback, null, _etFeedback.getPaddingRight(),
				RegularExpression.Normal, new InputBox.NoAnyAction() {
					@Override
					public void Action(EditText et, String regularExpression,
							Context context, View v, boolean hasFocus) {
						super.Action(et, regularExpression, context, v,
								hasFocus);
					}

					@Override
					public void OnFocusChange(boolean valide, boolean hasFocus) {
						super.OnFocusChange(valide, hasFocus);
						Log.d(Common.GetLineInfo(), "Focus -" + hasFocus);
						if (hasFocus) {
							showFeedback();
						} else {
							hideFeedback();
							Toast.makeText(getActivity(), "提交反馈意见失败",
									Toast.LENGTH_SHORT).show();
						}
					}
				});

		_sureToFeedback = activity.findViewById(R.id.MH_SureToFeedback);
		_sureToFeedback.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (_feedback.isValide())
					Common.toastInfo(getActivity(), "通知提交反馈意见");
				else
					Toast.makeText(getActivity(), "提交反馈意见失败",
							Toast.LENGTH_SHORT).show();
				hideFeedback();
			}

		});
	}

	private void hideFeedback() {
		_sureToFeedback.setVisibility(View.GONE);
		_etFeedback.setBackgroundColor(getActivity().getResources().getColor(
				R.color.Transparent));
	}

	private void showFeedback() {
		_sureToFeedback.setVisibility(View.VISIBLE);
		_etFeedback.setBackgroundColor(getActivity().getResources().getColor(
				R.color.TextBackground));
	}

	private void initData() {
		Activity activity = getActivity();

		initArrays(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				_list = (ArrayList<OrdersForm>) msg.obj;
				adapter.notifyDataSetChanged();
				pullListView.notifyDidDataLoad(false);
			}
		});

		pullListView
				.setOnPullDownListener(new PullDownView.OnPullDownListener() {

					@Override
					public void onRefresh() {
						getNewString(new Handler() {
							@Override
							public void handleMessage(Message msg) {

								showPartItems(_curfreshDBIdx);
								incDBIdx();

								adapter.notifyDataSetChanged();
								pullListView.notifyDidRefresh(_list.isEmpty());
							}
						});
					}

					@Override
					public void onLoadMore() {
						getNewString(new Handler() {
							@Override
							public void handleMessage(Message msg) {
								showPartItems(_curfreshDBIdx);
								incDBIdx();

								adapter.notifyDataSetChanged();
								pullListView.notifyDidLoadMore(_list.isEmpty());
							}
						});
					}
				});

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				_curSelected = position;
				OrdersForm of = (OrdersForm) adapter.getItem(position);
				Intent intent = new Intent();
				intent.setClass(getActivity(), OrderFormDetail.class);
				intent.putExtra(MSG.OrderForm, of);
				startActivityForResult(intent, _ReceiveOerdersForm);
			}
		});

		showPartItems(_curfreshDBIdx);
		_curfreshDBIdx += _refreshDBNumOneTime;
		if (_curfreshDBIdx > _totalDBOrdersFormNum)
			_curfreshDBIdx = _totalDBOrdersFormNum;
	}

	private void initArrays(final Handler handler) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(3000);
				} catch (Exception e) {
					Thread.interrupted();
					e.printStackTrace();
				}
				handler.obtainMessage(0, _list).sendToTarget();
			}
		}).start();
	}

	private void getNewString(final Handler handler) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(2000);
				} catch (Exception e) {
					Thread.interrupted();
					e.printStackTrace();
				}
				handler.obtainMessage(0,
						"New Text " + System.currentTimeMillis())
						.sendToTarget();
			}
		}).start();
	}

	private void addOrdersForm(int piecesNum) {
		for (int i = 0; i < piecesNum; ++i) {
			float totoalPrice = 0.0f;
			int nums = 3;
			int totalNum = 0;
			OrdersFormItem[] dies = new OrdersFormItem[nums];
			for (int j = 0; j < nums; ++j) {
				float unitPrice = 10.0f;
				int num = 3;
				dies[j] = new OrdersFormItem("香干炒肉" + j, unitPrice, num);
				totoalPrice += unitPrice * num;
				totalNum += num;
			}
			int id = new Random(System.currentTimeMillis()).nextInt();
			String address = "id -" + id;
			OrdersForm of = new OrdersForm(
					dies,
					id,
					totoalPrice,
					totalNum,
					"15676548990",
					address,
					"2013-" + String.format("%02d", Math.abs(id % 11) + 1)
							+ "-12 12:"
							+ String.format("%02d", Math.abs(id % 60)) + ":00",
					"一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十");

			addNewOrderFormToDB(of);

			Activity activity = getActivity();
			ExApplication exApp = (ExApplication) activity.getApplication();
			notifyYouHaveOrdersForm(activity, exApp._ImmdediateRing, address,
					totoalPrice + " " + totalNum + "份");
		}
	}

	public void notifyYouHaveOrdersForm(Context curContext, Uri ring,
			String title, String content) {
		NotificationManager mNotificationManager = (NotificationManager) curContext
				.getSystemService(Activity.NOTIFICATION_SERVICE);
		final Notification notification = new Notification(
				R.drawable.egg_smile, content, System.currentTimeMillis());
		
		RemoteViews rv = new RemoteViews(getActivity().getApplication()
				.getApplicationContext().getPackageName(), R.layout.notify);
		rv.setTextViewText(R.id.N_Title, title);
		rv.setTextViewText(R.id.N_Text, content);
		notification.contentView = rv;
		
		notification.contentIntent = PendingIntent.getActivity(curContext, 0,
				new Intent(curContext, Home.class), 0);
		// TYPE_RINGTONE - phone ring tone.
		notification.defaults = Notification.DEFAULT_LIGHTS
				| Notification.DEFAULT_VIBRATE;
		notification.sound = ring;
		notification.icon = R.drawable.egg_smile;

		// 把定义的notification 传递给 notificationmanager
		mNotificationManager.notify(0, notification);
	}

	private void addNewOrderFormToDB(OrdersForm of) {
		// Insert to DB.
		insertOneOrderFormToDB(of);
		int num = of.get_items().length;
		for (int i = 0; i < num; ++i)
			insertOneOrderFormItemToDB(of.get_items()[i], of.get_id());
	}

	private boolean removeOrderFormFromDB(int id) {
		boolean success = false;
		try {
			SQLiteDatabase db = _openDBHelper.getWritableDatabase();
			db.execSQL("PRAGMA foreign_keys=1;");
			db.delete(DBConstant._OrderFormTableName, DBConstant._OFTN_ID
					+ "==" + id, null);
			Log.d(Common.GetLineInfo(), "remove from database success");
			success = true;
		} catch (SQLException e) {
			Log.e(Common.GetLineInfo(), "remove from database failue");
		}

		return success;
	}

	private boolean insertOneOrderFormItemToDB(OrdersFormItem item, int id) {
		boolean success = false;
		SQLiteDatabase db = _openDBHelper.getWritableDatabase();
		String sql1 = "insert into " + DBConstant._OrderFormItemTableName
				+ " (" + DBConstant._OFITN_Name + ", "
				+ DBConstant._OFITN_UnitPrice + ", "
				+ DBConstant._OFITN_TotalNum + ", "
				+ DBConstant._OFITN_BelongOrderForm + ") values('"
				+ item.get_name() + "', " + item.get_unitPrice() + ", "
				+ item.get_totalNum() + ", " + id + ");";
		try {
			Log.d(Common.GetLineInfo(), "sql -" + sql1);
			db.execSQL(sql1);
			Log.d(Common.GetLineInfo(), "insert into database success");
			success = true;
		} catch (SQLException e) {
			Log.e(Common.GetLineInfo(),
					"insert into database failure" + e.getStackTrace());
		}

		return success;
	}

	private boolean insertOneOrderFormToDB(OrdersForm of) {
		boolean success = false;
		SQLiteDatabase db = _openDBHelper.getWritableDatabase();
		// time format: 2009-03-20 11:00:00
		String sql1 = "insert into " + DBConstant._OrderFormTableName
				+ " values(" + of.get_id() + ", " + of.get_totalPrice() + ", '"
				+ of.get_phoneNumber() + "', '" + of.get_address() + "', "
				+ of.get_totalNum() + ", datetime('" + of.get_time() + "'), '"
				+ of.get_remark() + "');";
		try {
			Log.d(Common.GetLineInfo(), "sql -" + sql1);
			db.execSQL(sql1);
			Log.d(Common.GetLineInfo(), "insert into database success");
			success = true;
		} catch (SQLException e) {
			Log.e(Common.GetLineInfo(),
					"insert into database failure" + e.getStackTrace());
		}

		return success;
	}

	private void incDBIdx() {
		_curfreshDBIdx += _refreshDBNumOneTime;
		Log.d(Common.GetLineInfo(), "activit -" + _Activity);
		if (_curfreshDBIdx < _totalDBOrdersFormNum) {
			if (_Activity != null)
				Toast.makeText(
						getActivity(),
						"接收到订单数量 [" + _curfreshDBIdx + "/"
								+ _totalDBOrdersFormNum + "]",
						Toast.LENGTH_SHORT).show();
		} else {
			_curfreshDBIdx = _totalDBOrdersFormNum;
			if (_Activity != null)
				Toast.makeText(
						getActivity(),
						"接收到订单数量 [" + _curfreshDBIdx + "/"
								+ _totalDBOrdersFormNum + "]",
						Toast.LENGTH_SHORT).show();
		}
	}

	private void desDBIdx() {
		--_curfreshDBIdx;
		Log.d(Common.GetLineInfo(), "_curfreshDBIdx -" + _curfreshDBIdx
				+ ", _totalDBOrdersFormNum -" + _totalDBOrdersFormNum);
	}

	private void showPartItems(long jumpIdx) {
		SQLiteDatabase db = _openDBHelper.getReadableDatabase();

		String col2[] = { DBConstant._OFTN_ID, DBConstant._OFTN_TotalPrice,
				DBConstant._OFTN_PhoneNumber, DBConstant._OFTN_Address,
				DBConstant._OFTN_TotalNum, DBConstant._OFTN_Time,
				DBConstant._OFTN_Remark };

		_totalDBOrdersFormNum = DBConstant.countTableRecordsNum(db,
				DBConstant._OrderFormTableName);
		// 查询数据
		Cursor cur = db.query(DBConstant._OrderFormTableName, null, null, null,
				null, null, DBConstant._OFTN_Time + " ASC" + " limit "
						+ jumpIdx + "," + _refreshDBNumOneTime);

		int num = cur.getCount();
		Log.d(Common.GetLineInfo(), "jumpIdx -" + jumpIdx
				+ ", records number -" + num);

		// TODO
		// 若为空
		for (int i = 0; i < num; i++) {
			if (cur.moveToFirst()) {// 判断游标是否为空
				cur.move(i);// 移动到指定记录

				int id = cur.getInt(cur.getColumnIndex(DBConstant._OFTN_ID));
				Cursor subCur = db.query(DBConstant._OrderFormItemTableName,
						null, DBConstant._OFITN_BelongOrderForm + "==" + id,
						null, null, null, null);
				int subNum = subCur.getCount();
				Log.d(Common.GetLineInfo(), "records number -" + subNum);

				OrdersFormItem[] ofi = new OrdersFormItem[subNum];
				for (int j = 0; j < subNum; ++j) {
					if (subCur.moveToFirst()) {// 判断游标是否为空
						subCur.move(j);// 移动到指定记录

						int dishNameIdx = subCur
								.getColumnIndex(DBConstant._DTN_DishName);
						Log.d(Common.GetLineInfo(), "dishNameIdx -"
								+ dishNameIdx);
						ofi[j] = new OrdersFormItem(
								subCur.getString(subCur
										.getColumnIndex(DBConstant._OFITN_Name)),
								subCur.getFloat(subCur
										.getColumnIndex(DBConstant._OFITN_UnitPrice)),
								subCur.getInt(subCur
										.getColumnIndex(DBConstant._OFITN_TotalNum)));
						Log.d(Common.GetLineInfo(), ofi[j].get_name() + ", "
								+ ofi[j].get_totalNum());
					}
				}
				subCur.close();

				OrdersForm of = new OrdersForm(
						ofi,
						cur.getInt(cur.getColumnIndex(DBConstant._OFTN_ID)),
						cur.getFloat(cur
								.getColumnIndex(DBConstant._OFTN_TotalPrice)),
						cur.getInt(cur
								.getColumnIndex(DBConstant._OFTN_TotalNum)),
						cur.getString(cur
								.getColumnIndex(DBConstant._OFTN_PhoneNumber)),
						cur.getString(cur
								.getColumnIndex(DBConstant._OFTN_Address)),
						cur.getString(cur.getColumnIndex(DBConstant._OFTN_Time)),
						cur.getString(cur
								.getColumnIndex(DBConstant._OFTN_Remark)));
				if (subNum > 0) {
					_list.add(of);
					Log.d(Common.GetLineInfo(), "list size -" + _list.size());
				}
			}
		}

		cur.close();
	}

	private void createMyHomeTables(SQLiteDatabase db) {
		// CREATE TABLE IF NOT EXISTS order_form(order_form_id INTEGER PRIMARY
		// KEY
		// , total_price REAL, phone_number TEXT, address TEXT,
		// total_num INTEGER, time DATETIME, remark TEXT);
		String orderFormSQL = "CREATE TABLE IF NOT EXISTS "
				+ DBConstant._OrderFormTableName + " (" + DBConstant._OFTN_ID
				+ " INTEGER PRIMARY KEY," + DBConstant._OFTN_TotalPrice
				+ " REAL, " + DBConstant._OFTN_PhoneNumber + " TEXT, "
				+ DBConstant._OFTN_Address + " TEXT, "
				+ DBConstant._OFTN_TotalNum + " TEXT, " + DBConstant._OFTN_Time
				+ " DATETIME, " + DBConstant._OFTN_Remark + " TEXT" + ");";
		Log.d(Common.GetLineInfo(), orderFormSQL);
		try {
			db.execSQL(orderFormSQL);
			Log.d(Common.GetLineInfo(), "Create table success");
		} catch (SQLException e) {
			Log.e(Common.GetLineInfo(),
					"Create table failure -" + e.getStackTrace());
		}

		// CREATE TABLE IF NOT EXISTS order_form_item(order_form_item_id integer
		// PRIMARY KEY
		// AUTOINCREMENT, name TEXT UNIQUE, unit_price REAL, total_num INTEGER,
		// belong_order_form INTEGER, FOREIGN KEY(belong_order_form) REFERENCES
		// order_form(order_form_id) ON DELETE CASCADE);
		String dishSQL = "CREATE TABLE  IF NOT EXISTS "
				+ DBConstant._OrderFormItemTableName + " ("
				+ DBConstant._OFITN_OrderFormItemID
				+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
				+ DBConstant._OFITN_Name + " TEXT, "
				+ DBConstant._OFITN_UnitPrice + " REAL, "
				+ DBConstant._OFITN_TotalNum + " INTEGER, "
				+ DBConstant._OFITN_BelongOrderForm + " INTEGER REFERENCES "
				+ DBConstant._OrderFormTableName + "(" + DBConstant._OFTN_ID
				+ ") ON DELETE CASCADE);";

		Log.d(Common.GetLineInfo(), dishSQL);
		try {
			db.execSQL(dishSQL);
			Log.d(Common.GetLineInfo(), "Create table success");
		} catch (SQLException e) {
			Log.e(Common.GetLineInfo(), "Create table failure");
		}

		DBConstant.createHistoryTables(db);
	}

	class ExAdapter extends BaseAdapter {
		private Context mContext;

		public ExAdapter(Context context) {
			mContext = context;
		}

		public void refresh(ArrayList<OrdersForm> list) {
			_list = list;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return _list.size();
		}

		@Override
		public Object getItem(int position) {
			return _list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public void notifyDataSetChanged() {
			super.notifyDataSetChanged();
			boolean hasData = getCount() > 0;
			pullListView.setVisibility(hasData ? View.VISIBLE : View.GONE);
			_noMsgLayout.setVisibility(!hasData ? View.VISIBLE : View.GONE);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder = null;
			if (convertView == null) {
				LayoutInflater inflater = LayoutInflater.from(mContext);
				convertView = inflater.inflate(R.layout.my_home_item, null);
				holder = new Holder();
				holder._dishName = (TextView) convertView
						.findViewById(R.id.HI_DishNames);
				holder._salesVolume = (TextView) convertView
						.findViewById(R.id.HI_SalesVolume);
				holder._time = (TextView) convertView
						.findViewById(R.id.HI_Time);
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}
			OrdersForm of = _list.get(position);
			OrdersFormItem[] di = of.get_items();
			Log.d(Common.GetLineInfo(), "position -" + position + ", " + di);
			String name = new String();
			int i = 0;
			for (; i < di.length; ++i)
				name += "[" + di[i].get_name() + "]";

			holder._dishName.setText(name);
			holder._salesVolume.setText("共" + of.get_totalNum() + "份");
			holder._time.setText(of.get_time());
			return convertView;
		}

		class Holder {
			private TextView _dishName, _salesVolume, _time;
		}
	}

}
